package com.tang.gulimall.product.service.impl;

import com.tang.gulimall.product.common.RedisCache;
import com.tang.gulimall.product.service.CategoryBrandRelationService;
import com.tang.gulimall.product.vo.Catelog2Vo;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.common.utils.PageUtils;
import com.tang.common.utils.Query;

import com.tang.gulimall.product.dao.CategoryDao;
import com.tang.gulimall.product.entity.CategoryEntity;
import com.tang.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listwithtree() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //找到所有的一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream()
                .filter(item -> item.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildrenCategoryEntity(getChildrens(menu, categoryEntities));
                    return menu;
                })
                .sorted((menu1, menu2) -> {

                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());

                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    @CacheEvict(value = {"category"},allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name")
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("方法执行了!");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }


    /**
     * 使用本地锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //先从缓存中获取数据
        Map<String, List<Catelog2Vo>> catalogJson = redisCache.getCacheMap("CatalogJson");
        if (catalogJson == null || catalogJson.size() == 0) {
            System.out.println("缓存没命中!");
            //缓存中没有 从数据库中查询并放入缓存
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonWithLocalLock();
            return catalogJsonFromDb;
        } else {
            //缓存中有直接从缓存中获取
            return catalogJson;
        }
    }


    /**
     * 使用分布式锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJson3() {
        //先从缓存中获取数据
        Map<String, List<Catelog2Vo>> catalogJson = redisCache.getCacheMap("CatalogJson");
        if (catalogJson == null || catalogJson.size() == 0) {
            System.out.println("缓存没命中!");
            //缓存中没有 从数据库中查询并放入缓存
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonWithFBLock();
            return catalogJsonFromDb;
        } else {
            //缓存中有直接从缓存中获取
            return catalogJson;
        }
    }

    /**
     * 使用分布式锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithFBLock() {
        //先向redis中设置值
        String token = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token, 300, TimeUnit.SECONDS);
        Map<String, List<Catelog2Vo>> catalogJsonFromDb = new HashMap<>();
        if (lock) {
            //设置成功 说明抢占了锁
            //获取返回数据
            try {
                catalogJsonFromDb = getCatalogJsonFromDbWithNoAnnotation();
            } finally {
                //删除锁 让其他线程进来
                //只删除自己的锁
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Object lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), token);
            }
            return catalogJsonFromDb;
        } else {
            //自循环 等待释放锁
            //睡眠300毫秒
            try {
                Thread.sleep(300);
            } catch (Exception e) {
                log.error(e.toString());
            }
            return getCatalogJsonWithFBLock();
        }
    }

    /**
     * 使用redisson分布式锁 使用注解
     *
     * @return
     */
    @Override
//    @Cacheable(value = {"category"},key = "#root.method.name")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //中有缓存没命中时才会走一下代码
        Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonWithNoRedis();
        return catalogJsonFromDb;
    }
    /**
     * 使用redisson分布式锁 不使用注解
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithNoAnnotation() {
        //先从缓存中获取数据
        Map<String, List<Catelog2Vo>> catalogJson = redisCache.getCacheMap("CatalogJson");
        if (catalogJson == null || catalogJson.size() == 0) {
            System.out.println("缓存没命中!");
            //缓存中没有 从数据库中查询并放入缓存
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJson3();
            return catalogJsonFromDb;
        } else {
            //缓存中有直接从缓存中获取
            return catalogJson;
        }
    }

    /**
     * 使用redisson分布式锁
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithRedissonLock() {
        RLock lock = redisson.getLock("CatalogJson-lock");
        //加锁 阻塞等待
        lock.lock();
        //先向redis中设置值
        Map<String, List<Catelog2Vo>> catalogJsonFromDb = new HashMap<>();
        try {
            catalogJsonFromDb = getCatalogJsonFromDbWithAnnotation();
        }finally {
            //释放锁
            lock.unlock();
        }
        return catalogJsonFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithAnnotation() {
        //确认缓存中没有 解决高并发下缓存击穿问题 只查一次数据库
        Map<String, List<Catelog2Vo>> catalogJson = redisCache.getCacheMap("CatalogJson");
        if (catalogJson != null && catalogJson.size() > 0) {
            //缓存中有数据
            return catalogJson;
        }
        System.out.println("查询了数据库.....");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonWithNoRedis() {
        System.out.println("查询了数据库.....");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithNoAnnotation() {
        //确认缓存中没有 解决高并发下缓存击穿问题 只查一次数据库
        Map<String, List<Catelog2Vo>> catalogJson = redisCache.getCacheMap("CatalogJson");
        if (catalogJson != null && catalogJson.size() > 0) {
            //缓存中有数据
            return catalogJson;
        }
        System.out.println("查询了数据库.....");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
        //2、封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            //2、封装上面面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //在放入缓存中
        redisCache.setCacheMap("CatalogJson", parent_cid);
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonWithLocalLock() {
        synchronized (this) {
            //确认缓存中没有 解决高并发下缓存击穿问题 只查一次数据库
            Map<String, List<Catelog2Vo>> catalogJson = redisCache.getCacheMap("CatalogJson");
            if (catalogJson != null && catalogJson.size() > 0) {
                //缓存中有数据
                return catalogJson;
            }
            System.out.println("查询了数据库.....");
            List<CategoryEntity> selectList = baseMapper.selectList(null);
            List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);
            //2、封装数据
            Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //1、每一个的一级分类，查到这个一级分类的二级分类
                List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
                //2、封装上面面的结果
                List<Catelog2Vo> catelog2Vos = null;
                if (categoryEntities != null) {
                    catelog2Vos = categoryEntities.stream().map(l2 -> {
                        Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        //1、找当前二级分类的三级分类封装成vo
                        List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                        if (level3Catelog != null) {
                            List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                                //2、封装成指定格式
                                Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catelog3Vo;
                            }).collect(Collectors.toList());
                            catelog2Vo.setCatalog3List(collect);
                        }
                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }
                return catelog2Vos;
            }));

            //在放入缓存中
            redisCache.setCacheMap("CatalogJson", parent_cid);
            return parent_cid;
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid().longValue() == parent_cid.longValue()).collect(Collectors.toList());
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return collect;
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }


    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> childrens = all.stream().filter(item -> {
            return item.getParentCid().longValue() == root.getCatId().longValue();
        }).map(item -> {
            item.setChildrenCategoryEntity(getChildrens(item, all));
            return item;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return childrens;
    }


}